package org.lwj.logger.name;

import org.lwj.logger.clazz.Loader;
import org.lwj.logger.name.support.JWarAppName;
import org.lwj.logger.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AppNameLoader extends Loader<AppName> {
	private final static Logger logger = LoggerFactory.getLogger(AppNameLoader.class);
	private static final JWarAppName jwarAppName = new JWarAppName();

	private static AppNameLoader loader = new AppNameLoader();

	public static AppNameLoader instance() {
		return loader;
	}

	private AppNameLoader() {
		addClazz("org.springframework.web.context.request.RequestContextHolder",
				"org.sky.logger.name.support.ContextPathAppName");
	}

	public Class<AppName> objectType() {
		return AppName.class;
	}

	/**
	 * 获取AppName
	 * 
	 * @return
	 */
	public static AppName loadAppName() {
		AppName appName = instance().getObject();
		if (appName == null) {
			appName = jwarAppName;
		}
		logger.info("Found the AppName is " + appName.getClass().getName());
		return appName;
	}

	/**
	 * 获取AppName
	 * 
	 * @return
	 */
	public static String appName() {
		String name = null;
		AppName appName = null;
		for (int i = 0; i < instance().size(); ++i) {
			try {
				appName = instance().getObject(i);
				name = appName.name();
				if (!Util.isEmpty(name)) {
					break;
				}
			} catch (Throwable e) {
			}
		}
		if (Util.isEmpty(name)) {
			appName = jwarAppName;
			name = appName.name();
		}
		logger.info(appName.getClass().getName() + " AppName is " + name);
		return name;
	}

}
